package com.aabte.nettyleran.netty.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/15
 */
public class ChineseProverbServer {

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        new ChineseProverbServer().run(port);
    }

    private void run(int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .handler(new ChineseProverbServerHandler());

        try {
            bootstrap.bind(port).sync().channel().closeFuture().await();
        } finally {
            group.shutdownGracefully();
        }
    }

    private static class ChineseProverbServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

        private final static String[] DICTIONARY = {
                "只要功夫深，铁杵磨成针。",
                "旧时王谢堂前燕，飞入寻常百姓家。",
                "洛阳亲友如相问，一片冰心在玉壶。",
                "一寸光阴一寸金，寸金难买寸光阴。",
                "老骥伏枥，志在千里。烈士莫年，壮心不已！"
        };

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        @Override
        protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
            String req = packet.content().toString(StandardCharsets.UTF_8);
            System.out.println("req = " + req);

            if ("谚语字典查询?".equals(req)) {
                ByteBuf byteBuf = Unpooled.copiedBuffer("谚语查询结果：" + nextQuote(), StandardCharsets.UTF_8);
                ctx.writeAndFlush(new DatagramPacket(byteBuf, packet.sender()));
            }
        }

        private String nextQuote() {
            int quoteId = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
            return DICTIONARY[quoteId];
        }
    }
}
